import {
  useRouter
} from "vue-router";
import {
  reactive,
  ref
} from "vue";
import {
  user
} from "@/store/user";
import {
  Toast
} from "@/utils/utils";
import {
  updatepassword
} from "@/api/user";

export function useRepassword() {
  const store = user();
  const router = useRouter();
  const drawerRef = ref("");
  const formRef = ref("");

  const password = reactive({
    oldpassword: "",
    password: "",
    repassword: "",
  });
  const rules = {
    oldpassword: [{
      required: true,
      message: "旧密码不能为空",
      trigger: "blur",
    }, ],
    password: [{
      required: true,
      message: "新密码不能为空",
      trigger: "blur",
    }, ],
    repassword: [{
      required: true,
      message: "确认密码不能为空",
      trigger: "blur",
    }, ],
  };
  const submit = () => {
    formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          let res = await updatepassword(password);
          if (res.data) {
            Toast("修改成功,请重新登录");
            let res = await store.logout();
            drawerRef.value.closeDrawer = false;
            router.push("/login");
          }
        } catch (error) {
          console.log(error);
        }
      } else {
        console.log("error submit!", fields);
      }
    });
  };
  return {
    drawerRef,
    password,
    rules,
    formRef,
    submit,
  };
}